package uit.minito.suggestion;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class SuggestionJSONParser {
	
	private static final String TAG_RESULTS="results";
	//private static final String TAG_FORMATTED_ADDRESS="formatted_address";
	private static final String TAG_GEOMETRY="geometry";
	private static final String TAG_LOCATION="location";
	private static final String TAG_LATITUDE="lat";
	private static final String TAG_LONGITUDE="lng";
	private static final String TAG_ADDRESS_COMPONENTS="address_components";
	private static final String TAG_LONG_NAME="long_name";
	public SuggestionJSONParser(){
		
	}
	
	public ArrayList<SuggestionModel> parse(String jsonString){
		ArrayList<SuggestionModel> resultList=new ArrayList<SuggestionModel>();
		try {
			JSONObject jsonBigParent=new JSONObject(jsonString);
			JSONArray results=jsonBigParent.getJSONArray(TAG_RESULTS);
			for(int i=0;i<results.length();i++){
				JSONObject iObject=results.getJSONObject(i);
				//get Address
				String address="";
				JSONArray addressComponents=iObject.getJSONArray(TAG_ADDRESS_COMPONENTS);
				for(int j=0;j<addressComponents.length();j++){
					JSONObject jObject =addressComponents.getJSONObject(j);
					String longName=jObject.getString(TAG_LONG_NAME);
					address+=(longName);
					if(j<addressComponents.length()-1){
						address+=", ";
					}
				}
				
				//get Coordinate
				JSONObject geometryObject=iObject.getJSONObject(TAG_GEOMETRY);
				JSONObject locationObject=geometryObject.getJSONObject(TAG_LOCATION);
				double latitude=locationObject.getDouble(TAG_LATITUDE);
				double longitude=locationObject.getDouble(TAG_LONGITUDE);
				SuggestionModel suggestion=new SuggestionModel(address, latitude, longitude);
				resultList.add(suggestion);
				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultList;
	}
}
